﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Ext.Net;
using BitPortal.Business;
using BitPortal.Models;
using BitPortal.Utils;
using System.Web.Security;
namespace BitPortal.Admin.Page
{
    public partial class Default : Controls.BaseAdminPage
    {
        protected override void OnInit(EventArgs e)
        {
            PermissionBLL.CheckRoleThrowException(role: "PageView", useExceptionHandler: true);
            base.OnInit(e);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindTreeNode();
            }
        }

        protected void BindTreeNode()
        {
            Ext.Net.TreeNode node = CreateNode(null);
            TreePanel1.Root.Add(node);
            TreePanel1.RootVisible = true;
        }

        protected Ext.Net.TreeNode CreateNode(PortalPage page)
        {
            //add curent page
            Ext.Net.TreeNode node = new Ext.Net.TreeNode("Trang gốc (không thể sửa/xóa)");
            node.NodeID = "0";
            if (page != null)
            {
                node.NodeID = page.PageID.ToString();
                node.Text = page.Name;
                if (page.IsBasePage)
                {
                    node.Icon = Icon.PageCancel;
                }
                else
                {
                    node.Icon = Icon.Page;
                }
            }
            //add childs pages 
            foreach (PortalPage ac in page.GetChilds())
            {
                node.Nodes.Add(CreateNode(ac));
            }
            //return node
            return node;
        }

        protected void TreePanel1_RemoteRename(object sender, RemoteRenameEventArgs e)
        {
            try
            {
                PermissionBLL.CheckRoleThrowException("PageEdit");
                e.Accept = true;
                int Id = Convert.ToInt32(e.NodeID);
                ExtendedBitPortalEntities bitExt = new ExtendedBitPortalEntities();
                PortalPage ac = bitExt.PortalPages.SingleOrDefault(ent => ent.PageID == Id);
                if (ac != null)
                {
                    ac.Name = e.NewText;
                    if (bitExt.SaveChanges() > 0) ShowNotification("Sửa đổi thành công trang mã : " + e.NodeID);
                }
            }
            catch (Exception ex)
            {
                ShowMessage(ex.Message);
            }

        }

        protected void TreePanel1_RemoteRemove(object sender, RemoteActionEventArgs e)
        {
            try
            {
                PermissionBLL.CheckRoleThrowException("PageDelete");
                PageBLL.Delete(e.NodeID.ToInt32TryParse());
                ShowNotification("Xóa thành công trang mã : " + e.NodeID);
                e.Accept = true;
            }
            catch (Exception ex)
            {
                ShowMessage(ex.Message);
            }
        }

        protected void TreePanel1_RemoteAppend(object sender, RemoteAppendEventArgs e)
        {
            try
            {
                PermissionBLL.CheckRoleThrowException("PageInsert");
                PortalPage page = new PortalPage()
                {
                    Name = e.Text,
                    ParentID = (e.ParentNodeID.Equals("0")) ? null : (int?)Convert.ToInt32(e.ParentNodeID),
                    Layout = "LeftSidebar"
                };
                if (page.Insert() > 0)
                {
                    e.Accept = true;
                    ShowNotification("Thêm thành công trang : " + e.Text);
                }
            }
            catch (Exception ex)
            {
                ShowMessage(ex.Message);
            }
        }

        protected void SubmitNode(object sender, DirectEventArgs e)
        {
            string nodeStr = e.ExtraParams["node"];
            Newtonsoft.Json.Linq.JObject node = JSON.Deserialize<Newtonsoft.Json.Linq.JObject>(nodeStr);
            string id = node.Property("nodeID").Value.ToString().Replace("\"", "");
            string path = node.Property("path").Value.ToString();
            PageAddEdit1.BindData(id.ToInt32TryParse());
        }

        protected void ShowModule(object sender, DirectEventArgs e)
        {
            string nodeStr = e.ExtraParams["node"];
            Newtonsoft.Json.Linq.JObject node = JSON.Deserialize<Newtonsoft.Json.Linq.JObject>(nodeStr);
            string id = node.Property("nodeID").Value.ToString().Replace("\"", "");
            string path = node.Property("path").Value.ToString();
            wModule.AutoLoad.Url = "/Admin/Page/ModuleInPage.aspx?PageID=" + id;
            wModule.LoadContent();
            wModule.Show();
        }

        protected void InsertNode(object sender, DirectEventArgs e)
        {
            string nodeStr = e.ExtraParams["node"];
            Newtonsoft.Json.Linq.JObject node = JSON.Deserialize<Newtonsoft.Json.Linq.JObject>(nodeStr);
            string id = node.Property("nodeID").Value.ToString().Replace("\"", "");
            string path = node.Property("path").Value.ToString();
            PageAddEdit1.BindData();
        }

        protected void TreePanel1_RemoteMove(object sender, RemoteMoveEventArgs e)
        {
            try
            {
                PermissionBLL.CheckRoleThrowException("PageEdit");
                int Id = Convert.ToInt32(e.NodeID);
                ExtendedBitPortalEntities bitExt = new ExtendedBitPortalEntities();
                PortalPage ac = bitExt.PortalPages.SingleOrDefault(ent => ent.PageID == Id);
                if (ac != null)
                {
                    ac.ParentID = (e.TargetNodeID.Equals("0")) ? null : (int?)Convert.ToInt32(e.TargetNodeID);
                    if (bitExt.SaveChanges() > 0)
                    {
                        e.Accept = true;
                        ShowNotification("Sửa đổi thành công trang mã : " + e.NodeID);
                    }
                }

            }
            catch (Exception ex)
            {
                ShowMessage(ex.Message);
            }
        }

        protected void BindTrash()
        {
            if (Roles.IsUserInRole("RootAdmin"))
            {
                Store1.DataSource = (new ExtendedBitPortalEntities()).PortalPages.Where(ent => ent.IsDeleted == true);
            }
            else
            {
                Store1.DataSource = (new ExtendedBitPortalEntities()).PortalPages.Where(ent => ent.IsDeleted == true && ent.IsBasePage == false);
            }
            Store1.DataBind();
        }

        protected void Store1_RefreshData(object sender, StoreRefreshDataEventArgs e)
        {
            BindTrash();
        }

        protected void btnTrashEmpty_Click(object sender, DirectEventArgs e)
        {
            try
            {
                PermissionBLL.CheckRoleThrowException("PageDelete");
                int record = 0;
                ExtendedBitPortalEntities bitEnt = new ExtendedBitPortalEntities();
                foreach (PortalPage ac in bitEnt.PortalPages.Where(ent => ent.IsDeleted == true))
                {
                    bitEnt.PortalPages.DeleteObject(ac);
                    record++;
                }
                ShowNotification("Xóa" + record + " trang trong thùng rác thành công!");
                BindTrash();
            }
            catch (Exception ex)
            {
                ShowMessage(ex.Message);
            }
        }

        protected void btnTrashDelete_Click(object sender, DirectEventArgs e)
        {
            try
            {
                PermissionBLL.CheckRoleThrowException("PageDelete");
                int record = 0;
                RowSelectionModel sm = this.GridPanel1.SelectionModel.Primary as RowSelectionModel;
                foreach (SelectedRow row in sm.SelectedRows)
                {
                    PageBLL.DeletePermanently(row.RecordID.ToInt32TryParse());
                    record++;
                }
                if (record > 0)
                {
                    ShowNotification("Xóa" + record + " trang trong thùng rác thành công!");
                    sm.ClearSelections();
                    BindTrash();
                }
            }
            catch (Exception ex)
            {
                ShowMessage(ex.Message);
            }
        }

        protected void btnUnDelete_Click(object sender, DirectEventArgs e)
        {
            try
            {
                PermissionBLL.CheckRoleThrowException("PageEdit");
                ExtendedBitPortalEntities bitEnt = new ExtendedBitPortalEntities();
                RowSelectionModel sm = this.GridPanel1.SelectionModel.Primary as RowSelectionModel;
                foreach (SelectedRow row in sm.SelectedRows)
                {
                    int ID = row.RecordID.ToInt32TryParse();
                    PortalPage ac = bitEnt.PortalPages.SingleOrDefault(ent => ent.PageID == ID);
                    if (ac != null)
                        ac.IsDeleted = false;
                }
                int record = bitEnt.SaveChanges();
                if (record > 0)
                {
                    ShowNotification("Bỏ xóa" + record + " trang trong thùng rác thành công!");
                    sm.ClearSelections();
                    BindTrash();
                }
            }
            catch (Exception ex)
            {
                ShowMessage(ex.Message);
            }
        }

    }
}